package com.tenbent.product.base.security.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tenbent.product.base.security.CustomAuthenticationSuccessHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

/**
 * 自定义认证成功处理类
 *
 * 此功能类似于(formLogin().loginPage("/login").defaultSuccessUrl("/home"))
 *
 * 所做的事情，也算是一种扩展
 *
 * @author Randy
 *
 *         Created by ThinkPad on 2017/6/16.
 */
public class CustomAuthenticationSuccessHandlerImpl extends SimpleUrlAuthenticationSuccessHandler
		implements CustomAuthenticationSuccessHandler {

	private String defaultUrl = "/eg/home";

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {

		// Todo 根据需求写自己业务代码，如果只是跳转统一页面则配置上使用 .defaultSuccessUrl("/home")代替此类
		// defaultUrl = determineTargetUrl(authentication);
		if (response.isCommitted()) {
			System.out.println("Can't redirect");
			return;
		}
		redirectStrategy.sendRedirect(request, response, defaultUrl);
	}

	/*
	 * 根据登录用户对应的角色跳转不同的页面
	 *
	 */
	protected String determineTargetUrl(Authentication authentication) {

		Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

		List<String> roles = new ArrayList<>();

		for (GrantedAuthority a : authorities) {
			roles.add(a.getAuthority());
		}
		if (isDba(roles)) {
			defaultUrl = "/dba";
		} else if (isAdmin(roles)) {
			defaultUrl = "/admin";
		} else if (isUser(roles)) {
			defaultUrl = "/home";
		} else {
			defaultUrl = "/denied";
		}
		return defaultUrl;
	}

	private boolean isUser(List<String> roles) {
		if (roles.contains("ROLE_USER")) {
			return true;
		}
		return false;
	}

	private boolean isAdmin(List<String> roles) {
		if (roles.contains("ROLE_ADMIN")) {
			return true;
		}
		return false;
	}

	private boolean isDba(List<String> roles) {
		if (roles.contains("ROLE_DBA")) {
			return true;
		}
		return false;
	}
}
